//
//  ClubMoreView.swift
//  77Club
//
//  Created by Apple on 2024/9/25.
//

import UIKit

class ClubMoreView: UIView, UITableViewDelegate, UITableViewDataSource, RaeAnimationProtocol, RaeAnimationDelegate {

    func animationContainerViewSize() -> CGSize {
        CGSize(width: .screenWidth, height: height)
    }
    
    func animationContainerViewStyle() -> RaeAnimationViewStyle {
        .bottom
    }
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubMoreItemCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.rowHeight = 70.0.Scale
        return tableView
    }()
    private let cancelButton = c_make_ex(UIButton.self)
        .corner(8.0.Scale).bgColor(.white).text("取消")
        .font(15.font_semiBold).color("#2E3033").end()
    private var shareView = ClubMoreShareView()
    private var height = 285.0.Scale
    
    var uid_des = "" {
        didSet{
            loadData()
        }
    }
    
    var del = false {
        didSet{
            loadPostData()
        }
    }
    
    var dataSource: [ClubMoreModel]?{
        didSet{
            guard let arr = dataSource else { return }
            tableView.heightConstraint?.constant = 70.0.Scale * Double(arr.count)
            height = 215 + (70.0.Scale * Double(arr.count))
            tableView.reloadData()
        }
    }
    
    var isPost = false
    private var models = [ClubMoreModel]()
    
    var copyShareBlock: ((_ type: Int) -> Void)?
    var reportBlock: (() -> Void)?
    var delBlock: (() -> Void)?
    var moreBlock: ((_ type: Int) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = "#E8E9EB".toColor
        rae.corner(12.0.Scale, corners: [.layerMinXMinYCorner,.layerMaxXMinYCorner])
        
        subviews{
            shareView
            tableView
            cancelButton
        }
        
        shareView.top(20.0.Scale).leading(16.0.Scale).trailing(16.0.Scale).height(103.0.Scale)
        tableView.leading(16.0.Scale).trailing(16.0.Scale).height(70.0.Scale)
        tableView.Top == shareView.Bottom + 10.0.Scale
        cancelButton.leading(16.0.Scale).trailing(16.0.Scale).height(45.0.Scale)
        cancelButton.Top == tableView.Bottom
        
        shareView.copyShareBlock = { type in
            self.entryAnimate.animation(dismiss: self){
                self.copyShareBlock?(type)
            }
        }
        cancelButton.addTarget(self, action: #selector(clickCancelButton), for: .touchUpInside)
    }
    
    private func loadData(){
        
        let dynamicTitle = isPost ? "帖子" : "动态"
        var title = "举报此\(dynamicTitle)"
        var img = "Home_more_report"
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid == uid_des {
            title = "删除\(dynamicTitle)"
            img = "Home_more_del"
        }
        
        let delModel = ClubMoreModel(title: title, img: img, isRed: true)
        models.append(delModel)
        
        tableView.heightConstraint?.constant = 70.0.Scale * Double(models.count)
        height = 215 + (70.0.Scale * Double(models.count))
        tableView.reloadData()
    }
    
    private func loadPostData(){
        
        self.isPost = true
        let dynamicTitle = "帖子"
        var title = "举报此\(dynamicTitle)"
        var img = "Home_more_report"
        if del {
            title = "删除\(dynamicTitle)"
            img = "Home_more_del"
        }
        
        let delModel = ClubMoreModel(title: title, img: img, isRed: true)
        models.append(delModel)
        
        self.tableView.reloadData()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if let arr = dataSource {
            return arr.count
        }else{
            return models.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubMoreItemCell", for: indexPath) as! ClubMoreItemCell
        if let arr = dataSource {
            cell.model = arr[indexPath.row]
        }else{
            cell.model = models[indexPath.row]
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if let arr = dataSource {
            let type = arr[indexPath.row].type
            entryAnimate.animation(dismiss: self){
                if type == 4 {
                    self.delBlock?()
                }else{
                    self.moreBlock?(type)
                }
            }            
        }else{
            let dynamicTitle = isPost ? "帖子" : "动态"
            entryAnimate.animation(dismiss: self){
                if self.models[indexPath.row].title == "删除\(dynamicTitle)"{
                    self.delBlock?()
                }else{
                    self.reportBlock?()
                }
            }
        }        
    }
    
    @objc private func clickCancelButton(){
        entryAnimate.animation(dismiss: self)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


class ClubMoreItemCell: UITableViewCell {
    
    private let bgView = c_make_ex(UIView.self)
        .bgColor(.white).corner(8.0.Scale).end()
    private let iconImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).end()
    private let titleLabel = c_make_ex(UILabel.self)
        .font(15.font_medium).end()

    var model: ClubMoreModel?{
        didSet{
            guard let md = model else { return }
            
            iconImageView.image = md.img.toImage
            titleLabel.text = md.title
            if md.isRed {
                titleLabel.textColor = "#B21212".toColor
            }else{
                titleLabel.textColor = "#47494D".toColor
            }
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            bgView.subviews{
                iconImageView
                titleLabel
            }
        }
        
        bgView.leading(0).trailing(0).top(0).bottom(10)
        iconImageView.leading(20.0.Scale).size(20.0.Scale).centerVertically()
        titleLabel.leading(52.0.Scale).centerVertically()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class ClubMoreShareView: UIView, UICollectionViewDelegate, UICollectionViewDataSource {

    private var nameString = ["分享至微信","分享至朋友圈","分享至QQ","复制链接"]
    private var imgString = ["Home_more_wechat","Home_more_circle","Home_more_QQ","Home_more_share"]
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    
    var copyShareBlock: ((_ type: Int) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = .clear
        
        let w = (CGFloat.screenWidth - 50.0.Scale)/3
        
        subviews{
            collectionView
        }
        
        collectionView.leading(0).trailing(0).top(10).bottom(0).height(85.0.Scale)
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 8.0.Scale
        layout.minimumInteritemSpacing = 8.0.Scale
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: w, height: 85.0.Scale)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(ClubMoreShareItemCell.self, forCellWithReuseIdentifier: ClubMoreShareItemCell.description())
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return nameString.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubMoreShareItemCell.description(), for: indexPath) as? ClubMoreShareItemCell else { return UICollectionViewCell() }
        cell.title = nameString[indexPath.row]
        cell.img = imgString[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        copyShareBlock?(indexPath.row + 1)
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


//MARK: 主线图⽂攻略cell
class ClubMoreShareItemCell: UICollectionViewCell {
    
    private let bgView = UIIconButton(style: .top(itemSpace: 8))
    
    var title:String = "" {
        didSet{
            bgView.setTitle(title, for: .normal)
        }
    }
    var img:String = "" {
        didSet{
            bgView.setImage(img.toImage, for: .normal)
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .clear
        backgroundColor = .clear
        
        contentView.subviews{
            bgView
        }
                
        bgView.fillContainer()

        // 设置按钮的标题和外观
        bgView.iconSize = CGSize(width: 24, height: 24)
        bgView.backgroundColor = .white
        bgView.setTitleColor("#4B4C4D".toColor, for: .normal)
        bgView.titleLabel?.font = 15.font_medium
        bgView.layer.cornerRadius = 8
        bgView.layer.masksToBounds = true
        bgView.isUserInteractionEnabled = false
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
